<!--  -->
<template>
    <div class="main_container">
        <div class="custform_nav">
            <div>
                <div class="im-export">
                    <el-button type="success" @click="triggerFileInput">重新导入</el-button>
                    <input type="file" ref="fileInput" v-show="false" @change="importData" accept=".xlsx, .xls, .csv" />
                    <div>
                        <el-button type="primary" @click="exportData">导出信息</el-button>   
                    </div>                 
                </div>
                <el-input v-model="search_data.business_id" size="medium" placeholder="请输入ID搜索" style="width: 200px;"/>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button type="success" @click="add">添加</el-button>
                <!-- 添加用户弹窗 -->
                <el-dialog v-model="dialogVisible"  width="25%">
                    <div class="add_title">
                        <p>添加业务信息</p>
                    </div>
                    <el-form ref="userForm" :model="add_data" label-width="100px">
                        <el-form-item label="客户ID">
                            <el-input v-model="add_data.customer_id" placeholder="请输入客户ID"></el-input>
                        </el-form-item>
                        <el-form-item label="负责人ID">
                            <el-input v-model="add_data.staff_id" placeholder="请输入负责人ID"></el-input>                         
                        </el-form-item>
                        <el-form-item label="业务类型">
                            <el-select v-model="add_data.type" placeholder="请选择业务类型">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label     "
                                    :value="item.value">
                                </el-option>
                            </el-select>                            
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-select v-model="add_data.state" placeholder="跟进状态">
                                <el-option
                                    v-for="item in options2"
                                    :key="item.value"
                                    :label="item.label     "
                                    :value="item.value">
                                </el-option>
                            </el-select>                              
                        </el-form-item>
                    </el-form>
                    <div class="add_btn">
                        <el-button @click="closeadd">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
        <el-table :data="business_tabledata" style="width: 100%">
            <el-table-column label="业务ID" prop="business_id" />
            <el-table-column label="客户姓名" prop="customer_name" />
            <el-table-column label="负责人" prop="staff_name" />
            <el-table-column label="业务类型" prop="type" :formatter="formattypeName"/>
            <el-table-column label="业务状态" prop="state" width="220%">
                <template #default="{ row }">
                    <el-steps :active="stateMap[row.state]" finish-status="success">
                        <el-step title="未跟进" :status="getStepStatus(0, row.state)"></el-step>
                        <el-step title="跟进中" :status="getStepStatus(1, row.state)"></el-step>
                        <el-step title="结束" :status="getStepStatus(2, row.state)"></el-step>
                    </el-steps>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_time">
                <template #default="scope">
                    {{ formatDate(scope.row.created_time) }}
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="updated_time">
                <template #default="scope">
                    {{ formatDate(scope.row.updated_time) }}
                </template>
            </el-table-column>
            <el-table-column align="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button type="warning" size="small" @click="update(scope.row)">
                            修改
                        </el-button>                   
                        <el-button
                            size="small"
                            type="danger"
                            @click="del(scope.row.business_id)"
                        >
                            删除
                        </el-button>
                    </el-button-group>                
                </template>
            </el-table-column>       
        </el-table>           
        <el-dialog v-model="dialogVisible_update"  width="25%">
            <div class="add_title">
                <p>修改业务信息</p>
            </div>
            <el-form ref="updateForm" :model="update_data" label-width="100px">
                <el-form-item label="客户ID">
                            <el-input v-model="update_data.customer_id" placeholder="请输入客户ID"></el-input>
                        </el-form-item>
                        <el-form-item label="负责人ID">
                            <el-input v-model="update_data.staff_id" placeholder="请输入负责人ID"></el-input>                         
                        </el-form-item>
                        <el-form-item label="业务类型">
                            <el-select v-model="update_data.type" placeholder="请选择业务类型">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label     "
                                    :value="item.value">
                                </el-option>
                            </el-select>                            
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-select v-model="update_data.state" placeholder="跟进状态">
                                <el-option
                                    v-for="item in options2"
                                    :key="item.value"
                                    :label="item.label     "
                                    :value="item.value">
                                </el-option>
                            </el-select>                              
                        </el-form-item>
            </el-form>
            <div class="add_btn">
                <el-button @click="closeupdate">取消</el-button>
                <el-button type="primary" @click="submitForm_update">确定</el-button>
            </div>
        </el-dialog>         
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import * as XLSX from 'xlsx';

const now = new Date().toISOString(); // 实时时间戳

const api = {
    searchurl: "/api/bus/search", 
    loadurl: "/api/bus",
    addurl: "/api/bus/add",
    updateurl: "/api/bus/update",   
    deleteurl: "/api/bus/delete",
    importurl: "/api/bus/import"        
};

const search_data = ref({
    business_id: ''
});

// 时间格式切换
function formatDate(isoString) {
    const date = new Date(isoString);
    const utcDate = new Date(date.toISOString()); // 确保输入是 UTC 时间
    utcDate.setUTCHours(utcDate.getUTCHours() - 8); // 转换为东八区时间

    const year = utcDate.getFullYear();
    const month = String(utcDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(utcDate.getDate()).padStart(2, '0');
    const hours = String(utcDate.getHours()).padStart(2, '0');
    const minutes = String(utcDate.getMinutes()).padStart(2, '0');
    const seconds = String(utcDate.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const business_tabledata = ref([]);

// *客户信息导出功能
const exportData = () => {
    // 创建一个工作簿
    const wb = XLSX.utils.book_new();

    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(business_tabledata.value);
    console.log(business_tabledata.value);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'business');

    // 导出文件
    XLSX.writeFile(wb, 'business.xlsx');
    ElMessage.success('导出成功');
};

//*客户信息导入
const importData = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
        // 使用 FileReader 读取文件内容
        const reader = new FileReader();
        reader.onload = (e) => {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0]; // 获取第一个
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet); // 将工作表转换为 JSON 格式

            // 转换为后端期望的格式
            const business = jsonData.map((row) => ({
                business_id: row['business_id'], 
                customer_id: row['customer_id'], 
                staff_id: row['staff_id'],
                type: row['type'],                
                created_time: new Date().toISOString(), 
                updated_time: new Date().toISOString() 
            }));

            // 发送 JSON 数据到后端
            axios.post(api.importurl, business, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                ElMessage.success('导入成功');
                console.log(response.data);
                loaddate(); // 刷新数据
            })
            .catch(error => {
                ElMessage.error('导入失败：' + error.message);
                console.error(error);
            });
        };
        reader.readAsBinaryString(file); // 读取文件内容
    } catch (error) {
        ElMessage.error('导入失败：' + error.message);
        console.error(error);
    }
};

const triggerFileInput = () => {
    const fileInput = document.querySelector('input[type="file"]');
    if (fileInput) {
        fileInput.click();
    }
};

// *搜索
const search = async () => {
    if (!search_data.value.business_id){ 
        loaddate(); 
        return;
    }
    try {
        let result = await axios.post(api.searchurl, {
            business_id: search_data.value.business_id
        });
        if(result.data){
            business_tabledata.value = [result.data];
            ElMessage.success('查询成功');
        }else{
            ElMessage.error('未匹配到相关查询');
        }
    } catch (error) {
        ElMessage.error('搜索失败:输入了非法字符或者长度不符');
        console.error(error);
    }
};

//*添加

const dialogVisible = ref(false); // 控制弹窗的显示与隐藏

const add_data = ref({
    business_id: null,
    customer_id: null, 
    staff_id: null,
    type: '',
    state: '',
    created_time: now,
    updated_time: now
});

const add = () => {
  dialogVisible.value = true;
};
const value = ref();

const options = ref([
    { value: "产品销售", label: "产品销售" },
    { value: "服务销售", label: "服务销售" },
    { value: "项目销售", label: "项目销售" },
    { value: "技术销售", label: "技术销售" }
]);

const options2 = ref([
    { value: "未跟进", label: "未跟进" },
    { value: "跟进中" , label: "跟进中" },
    { value: "结束" , label: "结束" }
]);

const closeadd = () => {
    add_data.value = {
        business_id: null,
        customer_id: null, 
        staff_id: null,
        type: '',
        state: '',
        created_time: now,
        updated_time: now
    };
    dialogVisible.value = false;
};

// 提交表单
const submitForm = async () => {
    try {
        const response = await axios.post(api.addurl, add_data.value);      
        ElMessage.success('用户添加成功');
        closeadd();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('添加失败：' + error.message);
        console.error(error);
    }
};

// *修改
const dialogVisible_update = ref(false); // 控制弹窗的显示与隐藏

const update_data = ref({
    business_id: null,
    customer_id: null, 
    staff_id: null,
    type: '',
    state: '',
    created_time: null,
    updated_time: now
});

const closeupdate = () => {
    update_data.value = {
        business_id: null,
        customer_id: null, 
        staff_id: null,
        type: '',
        state: '',
        created_time: null,
        updated_time: now
    };
    dialogVisible_update.value = false;
};

const update = (row) => {
    update_data.value.business_id = row.business_id;
    update_data.value.customer_id = row.customer_id;
    update_data.value.staff_id = row.staff_id;
    update_data.value.type = row.type;
    update_data.value.state = row.state;
    update_data.value.created_time = row.created_time;
    update_data.value.updated_time = row.updated_time;
    nextTick(() => {
        dialogVisible_update.value = true;
    });
};

const submitForm_update = async () => {
    try {        
        const response = await axios.put(`${api.updateurl}/${update_data.value.business_id}`, update_data.value);
        ElMessage.success('用户更新成功');
        console.log(response.data);
        closeupdate();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('更新失败：' + error.message);
        console.error(error);
    }
};

// *删除
const del = async (businessId) => {
    try {
        const confirmDelete = confirm("确定要删除该用户吗？");
        if (!confirmDelete) {
            return;
        }
        let result = await axios.delete(api.deleteurl + `/${businessId}`);
        ElMessage.success('删除成功');
        loaddate();
    } catch (error) {
        ElMessage.error('删除失败：' + error.message);
        console.error(error);
    }
};

// 刷新页面

// *加载
const loaddate = async () => {
    try {
        let result = await axios.get(api.loadurl);
        business_tabledata.value = result.data; 
        console.log(business_tabledata.value.state);
    } catch (error) {
        ElMessage.error('加载数据失败：' + error.message);
        console.error(error);
    }
};
  
loaddate();

const stateMap = {
    '未跟进': 0, // 第一步未完成
    '跟进中': 1, // 第一步完成，第二步进行中
    '结束': 2   // 所有步骤完成
};

// 获取步骤状态
function getStepStatus(stepIndex, currentState) {
    const activeStep = stateMap[currentState];
    if (stepIndex === activeStep) {
        return 'success'; // 当前步骤
    } else if (stepIndex < activeStep) {
        return 'wait'; // 已完成的步骤
    } else {
        return 'wait'; // 未完成的步骤
    }
}
</script>

<style scoped>

    .add_title{
        padding-bottom:20px;
    }
    .add_title>p{
        text-align: center;
        font-size: 20px;
    }

    .add_btn{
        padding: 10px;
        text-align: center;
    }

    .common-layout>ul {
        height: 80px;
    }
    .el-menu el-menu--horizontal el-menu-demo{
        min-width: 1588px;
    }
    .main_container{
        min-width: 80% ;

    }
    .custform_nav{
        margin: 20px;
    }
    .custform_nav>div{
        min-width: 380px;
        display: flex;

    }
    .im-export{
        display: flex;
        width: 200px;
        padding-right: 72%;
    }
    .im-export>button{
        margin-right:20px;
    }

</style>

